﻿using UnityEngine;
using System.Collections;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System;

namespace tcom.tools
{
	public class TEncodeFile : MonoBehaviour {
		
		//密钥
		private static string encryptKey = "44615649";
		//密钥向量
		private static byte[] Keys = {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF};
		/// <summary>
		/// 加密
		/// </param>
		public static byte[] EncryptDES(byte[] bytes)
		{
			
			try{
				byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
				byte[] rgbIV = Keys;
				byte[] inputByteArray = bytes;
				DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
				MemoryStream mStream = new MemoryStream();
				CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
			
				cStream.Write(inputByteArray, 0, inputByteArray.Length);
				cStream.FlushFinalBlock();
				return mStream.ToArray();
			}
			catch
			{
				return bytes;
			}
			
		}
		
		/// <summary>
		/// 解密
		/// </param>
		public static byte[] DecryptDES(byte[] inputByteArray)
		{
			try
			{
				byte[] rgbIV = Keys;
				DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
				MemoryStream mStream = new MemoryStream();
				CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(GetRgbKey(), rgbIV), CryptoStreamMode.Write);
				cStream.Write(inputByteArray, 0, inputByteArray.Length);
				cStream.FlushFinalBlock();
				return mStream.ToArray();
			}
			catch
			{
				return inputByteArray;
			}
		}
		
		public static byte[] GetBytes(string str_in, string code)
		{
			Encoding ec = Encoding.GetEncoding(code);
			if(ec != null)
			{
				return ec.GetBytes(str_in);
			}
			else
			{
				return new byte[1];
			}
		}
		
		static byte[] _rgbkey;
		static byte[] GetRgbKey()
		{
			if(_rgbkey == null)
			{
				_rgbkey = Encoding.UTF8.GetBytes(encryptKey);
			}
			return _rgbkey;
		}
		
		/// <summary>
		/// 解密
		/// </param>
		public static byte[] DecryptDES(ref byte[] inputByteArray)
		{
			try
			{
				byte[] rgbIV = Keys;
				DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
				MemoryStream mStream = new MemoryStream();
				CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(GetRgbKey(), rgbIV), CryptoStreamMode.Write);
				cStream.Write(inputByteArray, 0, inputByteArray.Length);
				cStream.FlushFinalBlock();
				return mStream.ToArray();
			}
			catch
			{
				return inputByteArray;
			}
		}
	}
}


